package com.cmsky.open.user.controller.admin;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.org.rapid_framework.web.scope.Flash;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.cmsky.open.core.base.BasePager;
import com.cmsky.open.core.util.JsonUtils;
import com.cmsky.open.core.util.PagerUitl;

import cn.org.rapid_framework.beanutils.BeanUtils;

import java.util.*;

import com.cmsky.open.core.base.*;
import com.cmsky.open.core.util.*;

import cn.org.rapid_framework.util.*;
import cn.org.rapid_framework.web.util.*;
import cn.org.rapid_framework.page.*;
import cn.org.rapid_framework.page.impl.*;

import com.cmsky.open.user.model.*;
import com.cmsky.open.user.dao.*;
import com.cmsky.open.user.enums.UserState;
import com.cmsky.open.user.exception.UserNotFoundExcetion;
import com.cmsky.open.user.exception.UserStateNotValidException;
import com.cmsky.open.user.manager.*;
import com.cmsky.open.user.vo.query.*;

/**
 * @author jandyfish email:jandyfish(a)gmail.com
 * @version 1.0
 * @since 1.0
 */


@Controller("admin.user.userMoneyInfo")
@RequestMapping("/admin/user/userMoneyInfo")
public class UserMoneyInfoController extends BaseSpringController{
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null; 
	
	private UserMoneyInfoManager userMoneyInfoManager;
	private UserInfoManager userInfoManager;
	
	private final String LIST_ACTION = "redirect:/admin/user/userMoneyInfo/list.do";
	
	public UserMoneyInfoController() {
	}
	
	/** 
	 * 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,注意大小写
	 **/
	public void setUserMoneyInfoManager(UserMoneyInfoManager manager) {
		this.userMoneyInfoManager = manager;
	}

	public void setUserInfoManager(UserInfoManager userInfoManager) {
		this.userInfoManager = userInfoManager;
	}

	/**
	 * 增加了@ModelAttribute的方法可以在本controller的方法调用前执行,可以存放一些共享变量,如枚举值
	 */
	@ModelAttribute
	public void init(ModelMap model) {
		model.put("now", new java.sql.Timestamp(System.currentTimeMillis()));
	}
	
	/** 
	 * 执行搜索 
	 **/
	@RequestMapping("list")
	public ModelAndView list(HttpServletRequest request,HttpServletResponse response,UserMoneyInfoQuery query) {
		BasePager page = this.userMoneyInfoManager.findPage(query);
		
		ModelAndView result = new ModelAndView("/admin/user/userMoneyInfo/list");
		result.addAllObjects(toModelMap(page, query));
		return result;
	}
	
	/**
	 * 默认管理页
	 */
	@RequestMapping("/index")
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response){
		return new ModelAndView("/admin/user/userMoneyInfo/index");
	}
	/**
	 * ajax搜索
	 * @param request
	 * @param response
	 * @param query
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/ajaxList")
	public String ajaxList(HttpServletRequest request,HttpServletResponse response,UserMoneyInfoQuery query) {
		BasePager<UserMoneyInfo> pager = this.userMoneyInfoManager.findPage(query);
		if(null!=pager && null!=pager.getRows()){
			for(UserMoneyInfo money : pager.getRows()){
				money.setUserInfo(this.userInfoManager.getById(money.getUserId()));
			}
		}
		return JsonUtils.jsonFromObject(PagerUitl.pasreToLigerMap(pager));
	}
	/**
	 * 批量更新或新增
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/saveOrUpdate")
	public String saveOrUpdate(HttpServletRequest request,HttpServletResponse response){
		String json = request.getParameter("json");
		Map<String,Object> result = new HashMap<String,Object>();
		String msg = null;
		List<Integer> successId = new LinkedList<Integer>();
		List tempList = JsonUtils.listFromJson(json);
		for(Object obj : tempList){
			UserMoneyInfo bean = JsonUtils.objectFromJson(JsonUtils.jsonFromObject(obj),UserMoneyInfo.class);
			if(null!=bean){
				int count = 0;
				if(null!=bean.getId() && bean.getId()<=0){
					try {
						count = this.userMoneyInfoManager.save(bean);
					} catch (UserNotFoundExcetion e) {
						msg="用户不存在";
					}catch(UserStateNotValidException e) {
						msg="用户状态不充值!";
					}
					bean.setId(count);
				}else{
					count = userMoneyInfoManager.update(bean);
				}
				if(count > 0){
					successId.add(bean.getId());
				}
			}
		}
		result.put("sucessList", successId);
		if(null != msg){
			result.put("msg", msg);
		}
		return JsonUtils.jsonFromObject(result);
	}
	
	/** 
	 * 查看对象
	 **/
	@RequestMapping("show")
	public ModelAndView show(HttpServletRequest request,HttpServletResponse response) throws Exception {
		java.lang.Integer id = new java.lang.Integer(request.getParameter("id"));
		UserMoneyInfo userMoneyInfo = (UserMoneyInfo)userMoneyInfoManager.getById(id);
		userMoneyInfo.setUserInfo(this.userInfoManager.getById(userMoneyInfo.getUserId()));
		return new ModelAndView("/admin/user/userMoneyInfo/show","userMoneyInfo",userMoneyInfo);
	}
	
	/** 
	 * 进入新增页面,获取用户信息，判断用户状态
	 **/
	@RequestMapping("create")
	public ModelAndView create(HttpServletRequest request,HttpServletResponse response,UserMoneyInfo userMoneyInfo) throws Exception {
		UserInfo userInfo = null;
		if(StringUtils.isNotBlank(request.getParameter("userId"))){
			userInfo = this.userInfoManager.getById(Integer.parseInt(request.getParameter("userId")));
		}else if(StringUtils.isNotBlank(request.getParameter("cardId"))){
			String cardId = request.getParameter("cardId");
			UserInfoQuery userQuery = new UserInfoQuery();
			userQuery.setCardId(cardId.trim());
			List<UserInfo> users= this.userInfoManager.findPage(userQuery).getRows();
			if(null == users || 0==users.size()){
				return AdminErrorUtil.getAdminErrorView(this.getClass(), "create", request, "新增充值", "相关用户不存在");
			}else if(1<users.size()){
				return AdminErrorUtil.getAdminErrorView(this.getClass(), "create", request, "新增充值", "相关用户信息错误");
			}else{
				userInfo = users.get(0);
				if(UserState.Configed == UserState.getByValue(userInfo.getState())){
					userMoneyInfo.setUserInfo(userInfo);
					userMoneyInfo.setUserId(userInfo.getId());
				}else{
					String msg = "用户"+userInfo.getName()+"状态为"+UserState.getByValue(userInfo.getState())+",不能进行充值";
					return AdminErrorUtil.getAdminErrorView(this.getClass(), "create", request, "新增充值", "相关用户信息错误");
				}
			}
		}
		return new ModelAndView("/admin/user/userMoneyInfo/create","userMoneyInfo",userMoneyInfo);
	}
	
	/** 
	 * 保存新增对象
	 **/
	@RequestMapping("save")
	public ModelAndView save(HttpServletRequest request,HttpServletResponse response,UserMoneyInfo userMoneyInfo) throws Exception {
		userMoneyInfoManager.save(userMoneyInfo);
		Flash.current().success(CREATED_SUCCESS); //存放在Flash中的数据,在下一次http请求中仍然可以读取数据,error()用于显示错误消息
		return new ModelAndView(LIST_ACTION);
	}
	
	/**
	 * 进入更新页面
	 **/
	@RequestMapping("edit")
	public ModelAndView edit(HttpServletRequest request,HttpServletResponse response) throws Exception {
		java.lang.Integer id = new java.lang.Integer(request.getParameter("id"));
		UserMoneyInfo userMoneyInfo = (UserMoneyInfo)userMoneyInfoManager.getById(id);
		userMoneyInfo.setUserInfo(this.userInfoManager.getById(userMoneyInfo.getUserId()));
		return new ModelAndView("/admin/user/userMoneyInfo/edit","userMoneyInfo",userMoneyInfo);
	}
	
	/**
	 * 保存更新对象
	 **/
	@RequestMapping("update")
	public ModelAndView update(HttpServletRequest request,HttpServletResponse response) throws Exception {
		java.lang.Integer id = new java.lang.Integer(request.getParameter("id"));
		
		UserMoneyInfo userMoneyInfo = (UserMoneyInfo)userMoneyInfoManager.getById(id);
		bind(request,userMoneyInfo);
		userMoneyInfoManager.update(userMoneyInfo);
		Flash.current().success(UPDATE_SUCCESS);
		return new ModelAndView(LIST_ACTION);
	}
	
	/**
	 *删除对象
	 **/
	@RequestMapping("delete")
	public ModelAndView delete(HttpServletRequest request,HttpServletResponse response) {
		String[] items = request.getParameterValues("items");
		for(int i = 0; i < items.length; i++) {
			Hashtable params = HttpUtils.parseQueryString(items[i]);
			
			java.lang.Integer id = new java.lang.Integer((String)params.get("id"));
			
			userMoneyInfoManager.removeById(id);
		}
		Flash.current().success(DELETE_SUCCESS);
		return new ModelAndView(LIST_ACTION);
	}
	
}

